package com.mszlu.blog.admin.service;

import com.mszlu.blog.admin.pojo.Admin;
import com.mszlu.blog.admin.pojo.Permission;
import com.sun.xml.internal.ws.resources.HttpserverMessages;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Select;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.Authenticator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2022/3/8
 * Time: 21:45
 *
 * @author sjp
 * Description: No Description
 */
@Service
@Slf4j
public class AuthService {
    @Resource
    private AdminService adminService;
    public boolean auth(HttpServletRequest httpServletRequest , Authentication authentication){
        String requestURI = httpServletRequest.getRequestURI();
        log.info("request uri :{}" ,requestURI);
        Object principal = authentication.getPrincipal();
        if(principal == null || "anonymousUser".equals(principal)){
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUserName(username);
        if(admin == null){
            return false;
        }
        Long id = admin.getId();
        log.info("当前用户id：{}",id);
        if(id == 1){
            //默认是超级管理员
            return true;
        }
        List<Permission> permissionList = this.adminService.findPermissionByAdmin(admin.getId());
        log.info("**{}",permissionList);
        requestURI = StringUtils.split(requestURI,"?")[0];
        for(Permission permission : permissionList){
            log.info("**{}",permission);
            if(requestURI.equals(permission.getPath())){
                log.info("**{}",requestURI);
                return true;
            }
        }
        return false;
    }

}
